package com.kunpan.admin.async;


import com.kunpan.admin.common.redis.RedisCache;
import com.kunpan.admin.common.utils.StringUtils;
import com.kunpan.admin.exception.email.EmailSendException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.MailParseException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.security.SecureRandom;

@Service
public class EmailService {
    private static final Logger logger = LoggerFactory.getLogger(EmailService.class);

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisCache redisCache;
    private final SecureRandom secureRandom = new SecureRandom();

    private static final String EMAIL_TEMPLATE = "<html><body>"
            + "<h3>%s,您的验证码是：</h3>"
            + "<div style='font-size:24px; color:#1890ff;'>%s</div>"
            + "<p>有效期2分钟，请勿泄露给他人</p>"
            + "</body></html>";
    private static final String from = "ikunnkun@qq.com";

    @Async("taskExecutor")
    public void sendVerificationCode(String toEmail, String codeKey, String countKey, String title) {
        try {
            String code = generateCode();
            sendHtmlEmail(toEmail, buildEmailContent(title, code));
            cacheVerificationCode(code, codeKey, countKey);
            logger.info("验证码发送成功，邮箱：{}", maskEmail(toEmail));
        } catch (MailException e) {
            logger.error("邮件发送失败: {}", e.getMessage());
            throw new EmailSendException("邮件发送失败", e);
        }
    }

    private String generateCode() {
        return String.format("%06d", secureRandom.nextInt(999999));
    }

    private void sendHtmlEmail(String to, String content) throws MailException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8");

        try {
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject("验证码通知");
            helper.setText(content, true); // true表示HTML内容
            mailSender.send(message);
        } catch (MessagingException e) {
            throw new MailParseException("邮件解析失败", e);
        }
    }

    private void cacheVerificationCode(String code, String key, String countKey) {
        redisCache.setCacheObject(key, code);
        //设置2分钟过期
        redisCache.expire(key, 60*2);
        // 记录发送次数
        if (redisCache.hasKey(countKey)) {
            Integer count = redisCache.getCacheObject(countKey);
            redisCache.setCacheObject(countKey, count + 1);
        } else {
            redisCache.setCacheObject(countKey, 1);
        }
        //设置过期时间2分钟
        redisCache.expire(countKey, 120);
    }

    private String maskEmail(String email) {
        if (StringUtils.isBlank(email)) return "";
        int atIndex = email.indexOf('@');
        return (atIndex > 2) ?
                email.substring(0, 2) + "***" + email.substring(atIndex) :
                "***" + email.substring(Math.max(0, email.length() - 4));
    }

    private String buildEmailContent(String title, String code) {
        return String.format(EMAIL_TEMPLATE, title, code);
    }
}
